package com.aaa.controller;

import com.aaa.entity.MyReturn;
import com.aaa.entity.PageSort;
import com.aaa.entity.User;
import com.aaa.service.UserService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.util.*;

/**
 * @author ：dudu（12232347710@qq.com）
 * @date ：Created in 2022/6/27 13:52
 * @description：
 * @modified By：
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController{
    MyReturn myReturn = new MyReturn();
    int num = 0;
    @Autowired
    private UserService userService;

    @RequestMapping("main.do")
    private String Pages() {
        return "showUser";
    }
    @RequestMapping("findAllUser.do")
    @ResponseBody
    public MyReturn findAll(PageSort pageSort) {
        Page page=userService.findAllUser(pageSort);
        //获取分页之后的数据
        myReturn.setData(page.getResult());
        //获取总条数
        myReturn.setCount(page.getTotal());
        return super.getSuccessResult(myReturn);
    }
    @RequestMapping ("addUsers.do")
    @ResponseBody
    public MyReturn addUser(User user) {
        System.out.println(user.getAvatar());
        String userName = user.getUserName();
        List<User> allName = userService.findAllName(userName);
        if (allName!=null&&allName.size()>0){
            super.getFailResult(myReturn);
            myReturn.setMsg("用户名重复");
        }else {
            Map<String, String> passwordSalt = super.makePasswordSalt(user.getPassword());
            // 把用户信息封装为一个用户实体
            user.setPassword(passwordSalt.get("password"));
            user.setSalt(passwordSalt.get("salt"));
            user.setCreateTime(new Date());
            num = userService.addUser(user);
            if (num > 0) {
                myReturn.setCode(0);
                myReturn.setMsg("添加成功");
            }
        }

        return myReturn;
    }
    @RequestMapping("deleteUser.do")
    @ResponseBody
    public MyReturn deleteUser(HttpServletRequest request) {
        // 获取前端传来的用户id，ids.join(",")返回的是字符串，所以需要用string接收
        String userid1 = request.getParameter("userId");
//        String useridStr = userinfo.getUserid().toString();
        // 把获取到的字符串拆分为 userid数组，分割条件是  逗号
        String[] userids = userid1.split(",");
        // 通过循环删除每一个 userid 对应的数据
        for (int i = 0; i < userids.length; i++) {
            Integer userid = Integer.parseInt(userids[i]);
            num = num + userService.deleteUser(userid);
        }
        // 通过num累计 判断是否全部删除，通常情况不会删除失败
        // 当前方法不完善，等待补充
        if (num >= userids.length) {
            super.getSuccessResult(myReturn);
        } else {
            super.getFailResult(myReturn);
        }
        return myReturn;
    }
    @RequestMapping ("updateUser.do")
    @ResponseBody
    public MyReturn updateUser(User user,String avatarUp){
        Map<String, String> passwordSalt = super.makePasswordSalt(user.getPassword());
        user.setPassword(passwordSalt.get("password"));
        user.setSalt(passwordSalt.get("salt"));
        // 更改用户信息
        user.setAvatar(avatarUp);
        user.setUpdateTime(new Date());
        num = userService.updateUser(user);
        if (num > 0) {
            super.getSuccessResult(myReturn);
        } else {
            super.getFailResult(myReturn);
        }
        return myReturn;
    }
    @RequestMapping ("updatePwd.do")
    @ResponseBody
    public MyReturn updatePwd(User user){
        Map<String, String> passwordSalt = super.makePasswordSalt(user.getPassword());
        user.setPassword(passwordSalt.get("password"));
        user.setSalt(passwordSalt.get("salt"));
        num = userService.resetPwd(user);
        if (num > 0) {
            super.getSuccessResult(myReturn);
        } else {
            super.getFailResult(myReturn);
        }
        return myReturn;
    }
    @RequestMapping ("imgUpload.do")
    @ResponseBody
    public MyReturn upload(MultipartFile file){
        //获取原始文件名
        String filename = file.getOriginalFilename();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId ="LTAI5tSBmtNxbJ6XkzMUVosu";
        String accessKeySecret ="9SMZljZMcJ30kw2d9Y0dsjXqw3RaN5";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "dufeifei";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        //上传之后的文件名
        String objectName =  UUID.randomUUID() + filename;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            /*String content = "Hello OSS";*/
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));
            /*ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));*/
            ossClient.putObject(putObjectRequest);
            Map<String, Object> map = new HashMap<>();
            map.put("src","https://dufeifei.oss-cn-hangzhou.aliyuncs.com/"+objectName);
            myReturn.setCode(0);
            myReturn.setMsg("成功");
            myReturn.setData(map);
            return myReturn;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        myReturn.setCode(1);
        myReturn.setMsg("失败");
        return myReturn;
    }
}
